﻿package kit4j.view.cs.swing.listener;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import kit4j.common.command.Command;
import kit4j.common.command.executor.CommandExecutor;
import kit4j.common.command.executor.SequentialCommandExecutor;

/**
 * 列表选择值发生更改时执行指定的命令的侦听器。 
 * 
 * @author MiniKnife
 *
 */
public class ExecuteCommandListSelectionListener implements
		ListSelectionListener {
	
	/**
	 * 命令的执行器。
	 */
	private CommandExecutor executor;
	
	public ExecuteCommandListSelectionListener() {
	}
	
	@Override
	public void valueChanged(ListSelectionEvent e) {
		try {
			createExecutor().execute();
		} catch (Throwable e1) {
			e1.printStackTrace();
		}
	}

	public  CommandExecutor getExecutor() {
		return executor;
	}

	public void setExecutor(CommandExecutor executor) {
		this.executor = executor;
	}
	
	/**
	 * 创建executor对象，如果executor对象当前为null，则默认创建一个SequentialCommandExecutor对象返回。
	 * @return 创建的executor
	 */
	private synchronized CommandExecutor createExecutor() {
		if(executor == null) {
			executor = new SequentialCommandExecutor();
		}
		
		return executor;
	}
	
	public void addCommand(Command cmd) {
		createExecutor().addCommand(cmd);
	}
	
	public void removeCommand(Command cmd) {
		createExecutor().removeCommand(cmd);
	}
	
}
